package io.renren.modules.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.exception.JshException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.dao.*;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.AccountHeadService;
import io.renren.modules.erp.vo.DepotHeadVo4List;
import io.renren.modules.sys.service.impl.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static io.renren.common.utils.Tools.getCenternTime;

@Service("accountHeadService")
public class AccountHeadServiceImpl extends ServiceImpl<AccountHeadMapper,AccountHead> implements AccountHeadService {
    private Logger logger = LoggerFactory.getLogger(AccountHeadServiceImpl.class);
    @Autowired
    private AccountHeadMapper accountHeadMapper;
    @Autowired
    private AccountHeadMapperEx accountHeadMapperEx;
    @Autowired
    private OrgaUserRelServiceImpl orgaUserRelService;
    @Autowired
    private AccountItemMapper accountItemMapper;

    @Autowired
    private AccountItemMapperEx accountItemMapperEx;

    @Autowired
    private AccountItemServiceImpl accountItemServiceImpl;

    public AccountHead getAccountHead(long id) throws Exception {
        AccountHead result = null;
        try {
            result = accountHeadMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<AccountHead> getAccountHeadListByIds(String ids) throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<AccountHead> list = new ArrayList<>();
        try {
            AccountHeadExample example = new AccountHeadExample();
            example.createCriteria().andIdIn(idList);
            list = accountHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<AccountHead> getAccountHead() throws Exception {
        AccountHeadExample example = new AccountHeadExample();
        List<AccountHead> list = null;
        try {
            list = accountHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list;
    }

    public PageUtils select(String type, String roleType, String billNo, String beginTime, String endTime, int currPage, int pageSize, Long userId) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.selectByConditionAccountHead(type, creatorArray, billNo, beginTime, endTime, page));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }


    public PageUtils getReceiptList(String billNo, String type, String status, String organName, String roleType, String beginTime, String endTime, int currPage, int pageSize, Long userId, String totalPriceMin, String totalPriceMax) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.getReceiptList(billNo, type, creatorArray, status, organName, beginTime, endTime, totalPriceMin, totalPriceMax, page));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }

     //付款单列表
    public PageUtils getPaymentList(String billNo, String type, String status, String organName, String roleType, String beginTime, String endTime, int currPage, int pageSize, Long userId, String totalPriceMin, String totalPriceMax, String paymentType) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.getPaymentList(billNo, type, creatorArray, status, organName, beginTime, endTime, totalPriceMin, totalPriceMax, page,paymentType));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }



    public PageUtils getVerificationList(String billNo, String type, String status, String organName, String roleType, String beginTime, String endTime, int currPage, int pageSize, Long userId, String totalPriceMin, String totalPriceMax, String serviceType) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.getVerificationList(billNo, type, creatorArray, status, organName, beginTime, endTime, totalPriceMin, totalPriceMax, page, serviceType));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }


    //应收帐
    public PageUtils getReceivableList(String type, String organName, String roleType, String beginTime, String endTime, int currPage, int pageSize, String userName, String receivablesBillno, Long userId) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.getReceivableList(type, creatorArray, organName, beginTime, endTime, userName, receivablesBillno, page));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }


    //应付帐
    public PageUtils getAccountableList(String type, String organName, String roleType, String beginTime, String endTime, int currPage, int pageSize, String userName, String accountpayBillno, Long userId) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;

        Page<AccountHeadVo4ListEx> page = new Page<>(currPage, pageSize);
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            page.setRecords(accountHeadMapperEx.getAccountableList(type, creatorArray, organName, beginTime, endTime, userName, accountpayBillno, page));
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
            page.setRecords(resList);
        }
        return new PageUtils(page);
    }


    public Long countAccountHead(String type, String roleType, String billNo, String beginTime, String endTime, Long userId) throws Exception {
        Long result = null;
        try {
            String[] creatorArray = getCreatorArray(roleType, userId);
            result = accountHeadMapperEx.countsByAccountHead(type, creatorArray, billNo, beginTime, endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    /**
     * 根据角色类型获取操作员数组
     *
     * @param roleType
     * @return
     * @throws Exception
     */
    private String[] getCreatorArray(String roleType, Long userId) throws Exception {
        String creator = "";

        if (BusinessConstants.ROLE_TYPE_PRIVATE.equals(roleType)) {
            creator = userId.toString();
        } else if (BusinessConstants.ROLE_TYPE_THIS_ORG.equals(roleType)) {
            creator = orgaUserRelService.getUserIdListByUserId(userId);
        }
        String[] creatorArray = null;
        if (StringUtil.isNotEmpty(creator)) {
            creatorArray = creator.split(",");
        }
        return creatorArray;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertAccountHead(String beanJson, HttpServletRequest request, Long userId) throws Exception {
        AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);
        int result = 0;
        try {
            accountHead.setCreator(userId);
            result = accountHeadMapper.insertSelective(accountHead);
//            logService.insertLog("财务",
//                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(accountHead.getBillNo()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateAccountHead(String beanJson, Long id, HttpServletRequest request) throws Exception {
        AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);
        accountHead.setId(id);
        int result = 0;
        try {
            result = accountHeadMapper.updateByPrimaryKeySelective(accountHead);
//            logService.insertLog("财务",
//                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(accountHead.getBillNo()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteAccountHead(Long id, HttpServletRequest request) throws Exception {
        int result = 0;
        try {
            AccountHead accountHead = accountHeadMapper.selectByPrimaryKey(id);
            result = accountHeadMapper.deleteByPrimaryKey(id);
//            logService.insertLog("财务",
//                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(accountHead.getBillNo()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAccountHead(String ids, HttpServletRequest request) throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        AccountHeadExample example = new AccountHeadExample();
        example.createCriteria().andIdIn(idList);
        int result = 0;
        try {
            result = accountHeadMapper.deleteByExample(example);
//            logService.insertLog("财务", "批量删除,id集:" + ids, request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name) throws Exception {
        AccountHeadExample example = new AccountHeadExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<AccountHead> list = null;
        try {
            list = accountHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list == null ? 0 : list.size();
    }

    public Long getMaxId() throws Exception {
        Long result = null;
        try {
            result = accountHeadMapperEx.getMaxId();
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    public BigDecimal findAllMoney(Integer supplierId, String type, String mode, String endTime) {
        String modeName = "";
        if (mode.equals("实际")) {
            modeName = "change_amount";
        } else if (mode.equals("合计")) {
            modeName = "total_price";
        }
        BigDecimal result = null;
        try {
            result = accountHeadMapperEx.findAllMoney(supplierId, type, modeName, endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    /**
     * 统计总金额
     *
     * @param getS
     * @param type
     * @param mode    合计或者金额
     * @param endTime
     * @return
     */
    public BigDecimal allMoney(String getS, String type, String mode, String endTime) {
        BigDecimal allMoney = BigDecimal.ZERO;
        try {
            Integer supplierId = Integer.valueOf(getS);
            BigDecimal sum = findAllMoney(supplierId, type, mode, endTime);
            if (sum != null) {
                allMoney = sum;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回正数，如果负数也转为正数
        if ((allMoney.compareTo(BigDecimal.ZERO)) == -1) {
            allMoney = allMoney.abs();
        }
        return allMoney;
    }

    /**
     * 查询单位的累计应收和累计应付，收预付款不计入此处
     *
     * @param supplierId
     * @param endTime
     * @param supType
     * @return
     */
    public BigDecimal findTotalPay(Integer supplierId, String endTime, String supType) {
        BigDecimal sum = BigDecimal.ZERO;
        String getS = supplierId.toString();
        int i = 1;
        if (("customer").equals(supType)) { //客户
            i = 1;
        } else if (("vendor").equals(supType)) { //供应商
            i = -1;
        }
        //收付款部分
        sum = sum.add((allMoney(getS, "付款", "合计", endTime).add(allMoney(getS, "付款", "实际", endTime))).multiply(new BigDecimal(i)));
        sum = sum.subtract((allMoney(getS, "收款", "合计", endTime).add(allMoney(getS, "收款", "实际", endTime))).multiply(new BigDecimal(i)));
        sum = sum.add((allMoney(getS, "收入", "合计", endTime).subtract(allMoney(getS, "收入", "实际", endTime))).multiply(new BigDecimal(i)));
        sum = sum.subtract((allMoney(getS, "支出", "合计", endTime).subtract(allMoney(getS, "支出", "实际", endTime))).multiply(new BigDecimal(i)));
        return sum;
    }

    public List<AccountHeadVo4ListEx> getDetailByNumber(String billNo) throws Exception {
        List<AccountHeadVo4ListEx> resList = new ArrayList<AccountHeadVo4ListEx>();
        List<AccountHeadVo4ListEx> list = null;
        try {
            list = accountHeadMapperEx.getDetailByNumber(billNo);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (null != list) {
            for (AccountHeadVo4ListEx ah : list) {
                if (ah.getChangeAmount() != null) {
                    ah.setChangeAmount(ah.getChangeAmount().abs());
                }
                if (ah.getTotalPrice() != null) {
                    ah.setTotalPrice(ah.getTotalPrice().abs());
                }
                ah.setBillTimeStr(getCenternTime(ah.getBillTime()));
                resList.add(ah);
            }
        }
        return resList;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAccountHeadByIds(String ids, Long userId) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<AccountHead> list = getAccountHeadListByIds(ids);
        for (AccountHead accountHead : list) {
            sb.append("[").append(accountHead.getBillNo()).append("]");
        }
//        logService.insertLog("财务", sb.toString(),
//                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        String[] idArray = ids.split(",");
        int result = 0;
        try {
            //删除主表
            result = accountItemMapperEx.batchDeleteAccountItemByHeadIds(new Date(), userId, idArray);
            //删除子表
            result = accountHeadMapperEx.batchDeleteAccountHeadByIds(new Date(), userId, idArray);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     * 正常删除，要考虑数据完整性，进行完整性校验
     * create time: 2019/4/10 15:49
     *
     * @return int
     * @Param: ids
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAccountHeadByIdsNormal(String ids, Long userId) throws Exception {
        /**
         * 校验
         * 1、财务子表	jsh_accountitem
         * 是否有相关数据
         * */
        int deleteTotal = 0;
        if (StringUtils.isEmpty(ids)) {
            return deleteTotal;
        }
        String[] idArray = ids.split(",");
        /**
         * 校验财务子表	jsh_accountitem
         * */
        List<AccountItem> accountItemList = null;
        try {
            accountItemList = accountItemMapperEx.getAccountItemListByHeaderIds(idArray);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (accountItemList != null && accountItemList.size() > 0) {
            logger.error("异常码[{}],异常提示[{}],参数,HeaderIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE, ExceptionConstants.DELETE_FORCE_CONFIRM_MSG, ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        /**
         * 校验通过执行删除操作
         * */
        deleteTotal = batchDeleteAccountHeadByIds(ids, userId);
        return deleteTotal;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(String status, String accountHeadIDs) throws Exception {
        List<Long> ids = StringUtil.strToLongList(accountHeadIDs);
        AccountHead accountHead = new AccountHead();
        accountHead.setStatus(status);
        AccountHeadExample example = new AccountHeadExample();
        example.createCriteria().andIdIn(ids);
        int result = 0;
        try {
            result = accountHeadMapper.updateByExampleSelective(accountHead, example);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }


    /**
     * 新增单据主表及单据子表信息   收款单/预收款单
     *
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addReceiptAndDetail(String beanJson, String rows, Long tenantId,
                                    HttpServletRequest request, Long userId, String numbers) throws Exception {

        /**处理单据主表数据*/
//        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);

        accountHead.setCreator(userId);

//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        accountHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try {
            accountHeadMapper.insertReceiptAndDetail(accountHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }


        List<Long> billNoList = accountHeadMapper.selectByBillNo(accountHead.getBillNo());
        if (billNoList != null) {
            Long headId = billNoList.get(0);
            //存到财务子表
            accountItemServiceImpl.saveReceiptItem(rows, headId, tenantId, request, userId);
            //将销货单/销售订单号 绑定到收款单，存放在中间表
            accountItemServiceImpl.saveAccountDepot(numbers, accountHead.getBillNo(), tenantId, request, userId);


        }



    }



    /**
     * 新增单据主表及单据子表信息   付款单/预付款单
     *
     * @param beanJson
     * @param rows
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addPaymentAndDetail(String beanJson, String rows, Long tenantId,
                                    HttpServletRequest request, Long userId, String numbers) throws Exception {

        /**处理单据主表数据*/
//        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);

        accountHead.setCreator(userId);

//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        accountHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try {
            accountHeadMapper.insertPaymentAndDetail(accountHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }


        List<Long> billNoList = accountHeadMapper.selectByBillNo(accountHead.getBillNo());
        if (billNoList != null) {
            Long headId = billNoList.get(0);
            //存到财务子表
            accountItemServiceImpl.saveReceiptItem(rows, headId, tenantId, request, userId);
            //将进货单/采购订单号 绑定到收款单，存放在中间表
            accountItemServiceImpl.saveAccountDepot(numbers, accountHead.getBillNo(), tenantId, request, userId);


        }



    }



    /**
     * 新增单据主表及单据子表信息   销向核销单
     *
     * @param beanJson
     * @param
     * @param tenantId
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addVerification(String beanJson,  Long tenantId,
                                HttpServletRequest request, Long userId, String numbers) throws Exception {
        /**处理单据主表数据*/
//        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);

        accountHead.setCreator(userId);

//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        accountHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        try {
            accountHeadMapper.insertReceiptAndDetail(accountHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }


        List<Long> billNoList = accountHeadMapper.selectByBillNo(accountHead.getBillNo());
        if (billNoList != null) {
            Long headId = billNoList.get(0);
            //存到财务子表
//            accountItemServiceImpl.saveReceiptItem(rows, headId, tenantId, request, userId);
            //将销货单/销售订单号 绑定到收款单，存放在中间表
            accountItemServiceImpl.saveAccountDepot(numbers, accountHead.getBillNo(), tenantId, request, userId);


        }



    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateReceiptAndDetail(Long id, String beanJson, String rows, Long tenantId, HttpServletRequest request, Long userId, String numbers) throws Exception {
        /**更新单据主表信息*/
            AccountHead accountHead = JSONObject.parseObject(beanJson, AccountHead.class);
            //判断用户是否已经登录过，登录过不再处理
            accountHead.setId(id);
            try {
                accountHeadMapper.updateByPrimaryKeySelective(accountHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e);
            }

            //存到财务子表
            accountItemServiceImpl.saveReceiptItem(rows, accountHead.getId(), tenantId, request, userId);
            //将销货单/销售订单号 绑定到收款单，存放在中间表
            accountItemServiceImpl.saveAccountDepot(numbers, accountHead.getBillNo(), tenantId, request, userId);
    }



}